package org.fioma.tree.bytes;

import java.util.ArrayList;
import java.util.List;

import org.fioma.tree.LabelRefFactory;

public class LabelRefBytesIndexFactory implements LabelRefFactory<LabelRefBytesIndex, BytesIndexed> {

	private ArrayList<LabelRefBytesIndex> poolLabels = new ArrayList<LabelRefBytesIndex>(100);
	private int nextLabelObject = 0;
	private ArrayList<BytesIndexed> poolBytesIndexed = new ArrayList<BytesIndexed>(100);
	private int nextBytesIndexedObject = 0;

	List<byte[]> words;

	public LabelRefBytesIndexFactory(List<byte[]> words) {
		this.words = words;
	}

	public LabelRefBytesIndex createLabel(int index, int start, int length) {
		return createLabel(createBytesIndexed(words.get(index), index), start, length);
	}

	@Override
	public LabelRefBytesIndex createLabel(BytesIndexed word) {
		return createLabel(word, 0, word.getWord()[0]);
	}

	@Override
	public LabelRefBytesIndex createLabel(BytesIndexed word, int start, int length) {
		LabelRefBytesIndex ret;
		if (nextLabelObject < poolLabels.size()) {
			ret = poolLabels.get(nextLabelObject);
			nextLabelObject++;
			ret.setWord(word);
			ret.setStart(start);
			ret.setLength(length);
		} else {
			ret = new LabelRefBytesIndex(word, start, length, this);
			poolLabels.add(ret);
			nextLabelObject++;
		}
		return ret;
	}

	public BytesIndexed createBytesIndexed(byte[] word, int index) {
		BytesIndexed ret;
		if (nextBytesIndexedObject < poolBytesIndexed.size()) {
			ret = poolBytesIndexed.get(nextBytesIndexedObject);
			nextBytesIndexedObject++;
			ret.setWord(word);
			ret.setIndex(index);
		} else {
			ret = new BytesIndexed(word, index);
			poolBytesIndexed.add(ret);
			nextBytesIndexedObject++;
		}
		return ret;
	}

	public void freeObjects() {
		nextLabelObject = 0;
		nextBytesIndexedObject = 0;
	}

}
